package com.system.module.oss.strategy;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.system.module.oss.common.enums.FileUploadTypeEnums;
import com.system.module.oss.factory.StrategyFactory;
import com.system.module.system.entity.SysOss;
import com.system.module.system.service.ISysOssService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * 阿里云oss文件上传策略
 *
 * @author 程序员Mars
 * @version 1.0
 * @date 2024-02-29 09:21:50
 */
@Slf4j
@Service
public class AliOssStrategy extends AbstractOssStrategy implements Strategy {

    @Resource
    private ISysOssService sysOssService;


    @Override
    public String upload(MultipartFile file) {
        String uploadUrl = null;
        SysOss ossConfig = this.getOssConfig();
        String endPoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKey();
        String accessKeySecret = ossConfig.getSecretKey();
        String bucketName = ossConfig.getBucketName();
        try {
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + uuid + fileName;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
            ossClient.shutdown();
            uploadUrl = "https://" + bucketName + "." + endPoint + "/" + fileName;
            log.info("阿里云oss图片地址:{}", uploadUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadUrl;
    }


    @Override
    public void afterPropertiesSet() {
        StrategyFactory.register(FileUploadTypeEnums.ALI_OSS, this);
    }

    @Override
    public SysOss getOssConfig() {
        List<SysOss> list = sysOssService.list(FileUploadTypeEnums.ALI_OSS.getType());
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("oss未配置");
        }
        return list.get(0);
    }
}
